import React, { useState } from "react"
import { View, Picker, Text } from "@tarojs/components"
import moment from "moment";
import Page from "@/components/page"
import PageNav from "@/components/pageNav";
import { useDidShow, usePullDownRefresh } from "@tarojs/taro";
import MonthColumnChart from "./monthColumnChart";
import MonthPieChart from "./MonthPieChart";
import Ranking from "./ranking";
import account from "@/store/account";
import viewMode from "@/store/viewMode";
import { observer } from "mobx-react";
import './index.scss'
import Taro from "@tarojs/taro";

const CountPage: React.FC = observer(() => {
  const years = [moment().year() - 2, moment().year() - 1, moment().year(), moment().year() + 1]
  const [year, setYear] = useState(moment().year())
  const [month, setMonth] = useState<string>()
  const [pageKey, setPageKey] = useState<number>()
  const [filterData, setFilterData] = useState<{
    name: string,
    itemId: number,
    categoryType: string
    moneyType: string
  }>()

  const yearsChange = (e) => {
    setYear(years[e.target.value])
  }
  const monthSelect = (monthData) => {
    setMonth(`${monthData.month}-01`)
    setFilterData(undefined)
  }
  const pieSelect = (res) => {
    if (res) {
      const { name, itemId, categoryType, moneyType } = res
      setFilterData({ name, itemId, categoryType, moneyType })
    } else {
      setFilterData(undefined)
    }
  }

  usePullDownRefresh(() => {
    setPageKey(Math.random)
    setTimeout(() => {
      Taro.stopPullDownRefresh();
    }, 100)
  })

  useDidShow(() => {
    setPageKey(account.accountIndex)
  })

  return <Page className="count-page page-background need-filter text-main-color flex-column flex-item" key={pageKey}>
    <PageNav className="count-page-header">
      <Picker mode='selector' range={years} onChange={yearsChange}>
        <View className='picker'>
          <Text>统计年份：{year}</Text>
          <Text className="iconfont icon-base-down"></Text>
        </View>
      </Picker>
    </PageNav>
    <MonthColumnChart year={year} onSelect={monthSelect}></MonthColumnChart>
    {
      !viewMode.categoryVisible ? <>
        <MonthPieChart onSelect={pieSelect} month={month}></MonthPieChart>
        <Ranking month={month} filterData={filterData}></Ranking>
      </> : null
    }
  </Page>
})

export default CountPage